package com.dw.love.dwade.utils;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.widget.ImageView;

import com.dw.love.dwade.R;

/**
 * Created by luozizhao on 2018/6/14.
 */

public class LruCachePicUtils {

    private static final String TAG = "LruCachePicUtils";
    private static LruCachePicUtils instants;
    private final LruCache<String, Bitmap> mLruCache;

    public LruCachePicUtils() {
        long maxMemory = Runtime.getRuntime().maxMemory();
        Log.d(TAG, "LruCachePicUtils: maxMemory:" + maxMemory);
        long memorySize = maxMemory / 4;
        mLruCache = new LruCache<String, Bitmap>((int) memorySize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getByteCount();
            }
        };
    }

    public static LruCachePicUtils getInstants() {
        if (instants == null) {
            synchronized (LruCachePicUtils.class) {
                if (instants == null) {
                    instants = new LruCachePicUtils();
                }
            }
        }
        return instants;
    }

    public Bitmap getBitmap(int resId) {
        String res = String.valueOf(resId);
        return mLruCache.get(res);
    }

    public Bitmap getBitmap(String path) {
        return mLruCache.get(path);
    }


    public void setBitmap(String path, Bitmap bitmap) {

        if (mLruCache.get(path) == null) {
            mLruCache.put(path, bitmap);
        }
    }

    public void loadBitmap(ImageView view, Bitmap bitmap) {
        if (bitmap!=null) {
            view.setImageBitmap(bitmap);
        } else {
            Log.d(TAG, "loadBitmap: loadBitmap失败");
        }
    }

    public void loadImageRes(ImageView view, int imgRes) {
        Bitmap bitmap = mLruCache.get(String.valueOf(imgRes));
        if (bitmap!=null) {
            view.setImageBitmap(bitmap);
        }else {
            view.setImageResource(R.drawable.icon_placeholder);
        }
    }

}